package com.bds.btcdc.adapter.huobi.market.http;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.bds.btcdc.model.CoinPairExchanges;
import com.bds.btcdc.util.EhcacheUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.bds.btcdc.adapter.service.IAdapterService;
import com.bds.btcdc.http.HttpUtil;
import com.bds.btcdc.model.MarketData;
import com.bds.btcdc.api.model.Result;
import com.bds.btcdc.util.Const;

@Service
public class HuobiService implements IAdapterService {
    private Logger logger = LoggerFactory.getLogger(getClass());

	private static final DecimalFormat df = new DecimalFormat("#0.00");

	private static final List<String> bds_pair=new ArrayList<String>();

	private void initPairs(List<CoinPairExchanges> pairs){
        for (int i = 0; i < pairs.size(); i++) {
            bds_pair.add(pairs.get(i).getEn_pair_code());
        }
    }

	public Result getMarketInfo(List<CoinPairExchanges> pairs) {
        if (bds_pair.size()==0)
            initPairs(pairs);
        Result rst = new Result();
		List<MarketData> ms = new ArrayList<MarketData>();
		try {
			HttpUtil httpUtil = HttpUtil.getInstance();

            for (int i = 0; i < pairs.size(); i++) {
                String pair=pairs.get(i).getPair_code();
                String param = "?symbol="+pair;
                Map<String, String> header = new HashMap<>();
                header.put("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.71 Safari/537.36");
                header.put("Content-Type", "application/x-www-form-urlencoded");
                String json = httpUtil.get(Const.HUOBI.URL + Const.HUOBI.WS_MARKET_INFO + param, header, false);
//                logger.info("请求地址为>>>>>>>>>>" + Const.HUOBI.URL + Const.HUOBI.WS_MARKET_INFO + param);
//                logger.info("火币行情更新>>>" + json);
                if (json==null)
                    throw new Exception("火币行情获取失败");
                JSONObject object = JSONObject.parseObject(json);
                String status = (String) object.get("status");
                if (status.equals("ok")) {
                    MarketData huobi_data = new MarketData();
                    JSONObject tick = object.getJSONObject("tick");
                    JSONArray ask = tick.getJSONArray("ask");
                    JSONArray bid = tick.getJSONArray("bid");
                    String last=df.format(tick.getBigDecimal("close"));
                    huobi_data.setLast(last);
                    huobi_data.setHigh(df.format(tick.getBigDecimal("high")));
                    huobi_data.setVol(df.format(tick.getBigDecimal("amount")));
                    huobi_data.setLow(df.format(tick.getBigDecimal("low")));
                    huobi_data.setBuy(df.format(bid.getBigDecimal(0)));
                    huobi_data.setSell(df.format(ask.getBigDecimal(0)));
                    huobi_data.setTimestamp(System.currentTimeMillis());
                    huobi_data.setPair(bds_pair.get(i));
                    huobi_data.setExchange(Const.HUOBI.EXCHANGE);
                    ms.add(huobi_data);

                    try {
                        //usdt 币对的最新交易价格存到缓存（资产情况统计时 使用）
                        if (pair.toUpperCase().contains("USDT") || pair.toUpperCase().contains("USD")) {
                            EhcacheUtils.getInstance().putCache(Const.HUOBI.EXCHANGE + "#" + pair,last);
                        }
                    }catch (Exception e){
                        logger.info("HUOBI:USDT币对的最新交易价格存到缓存 失败");
                    }
                }
            }
            rst.setData(ms);
            rst.setResult(Const.SUC,ms);
            return rst;

		} catch (Exception e) {
			logger.error("", e);
            return new Result(Const.FAIL_500, "错误");
        }
	}
}
